import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Offer_32_1 {
    /**
     * 剑指 Offer 32 - I. 从上到下打印二叉树
     * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
     */
    public static int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
//        int[] resultArray = new int[10000];
        //借助队列的先进先出
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<Integer>();
//        int index =0;
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
//                resultArray[index++]=treeNode.val;
            list.add(treeNode.val);
            if (treeNode.left != null) {
                queue.offer(treeNode.left);
            }
            if (treeNode.right != null) {
                queue.offer(treeNode.right);
            }
        }
//        int[] tempArray = new int[index];
//        for (int i = 0; i < tempArray.length; i++) {
//            tempArray[i]=resultArray[i];
//        }
        int[] tempArray = new int[list.size()];
        for (int i = 0; i < tempArray.length; i++) {
            tempArray[i] = list.get(i);
        }

        return tempArray;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);

        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);

        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode2.right = treeNode5;
        int[] resultArray = levelOrder(treeNode1);
        for (int i = 0; i < resultArray.length; i++) {
            System.out.println(resultArray[i]);
        }
    }
}
